<template>
    <div class="execute-result-box">
        <vxe-toolbar ref="xToolbar" size="small" class-name="execute-result-table-toolbar">
            <template #buttons>
                <el-tooltip effect="light" content="添加记录" placement="top-start">
                    <el-button icon="el-icon-plus" plain circle size="small" :disabled="!item.editAuth"
                        @click="insertHandle(item)" />
                </el-tooltip>
                <el-tooltip effect="light" content="删除记录" placement="top-start">
                    <el-button icon="el-icon-minus" plain circle size="small" @click="deleteHandle"
                        :disabled="!(item.editAuth && deleteCheckboxState)" />
                </el-tooltip>
                <el-tooltip effect="light" content="提交更改" placement="top-start">
                    <el-button icon="el-icon-check" plain circle size="small" @click="submitEditHandle"
                        :disabled="!(item.editAuth && dataEditState)" />
                </el-tooltip>
                <el-tooltip effect="light" content="放弃更改" placement="top-start">
                    <el-button icon="el-icon-close" plain circle size="small" @click="cancelEditHandle"
                        :disabled="!(item.editAuth && dataEditState)" />
                </el-tooltip>
                <el-tooltip effect="light" content="刷新" placement="top-start">
                    <el-button icon="el-icon-refresh-left" plain circle size="small" @click="refreshDataHandle" />
                </el-tooltip>
            </template>
            <template #tools>
                <el-tooltip effect="light" content="是否开启分页" placement="top-start">
                    <el-switch v-model="item.noPage" size="small" :active-value="false" plain inline-prompt
                        :inactive-value="true" @change="executeResultPageHandle" />
                </el-tooltip>
            </template>
        </vxe-toolbar>
        <div :style="{ height: executeResultResizerValue1 }">
            <vxe-table :data="item.rows" size="mini" border stripe auto-resize height="auto" :keep-source="true" align="left"
                :loading="tableLoading"
                ref="xTable" show-overflow :index="index" class="mytable-scrollbar" :column-config="{ resizable: true }"
                :row-config="{ isHover: true, isCurrent: true }"
                :edit-config="{ trigger: 'click', mode: 'row', enabled: item.editAuth }"
                @cell-click="executeResultCellHandle" @checkbox-change="checkboxChangeHandle"
                @checkbox-all="checkboxChangeHandle" @edit-actived="dataEditStateHandle" @edit-closed="dataEditStateHandle"
                :id="item">
                <vxe-column type="checkbox" width="60"></vxe-column>
                <vxe-column v-for="columns in item.columns " :field="columns.field" :cell-type="columns.type"
                    show-header-overflow="title" show-overflow="title" :title="columns.field" width="160"
                    :edit-render="{ autofocus: '.vxe-input--inner' }" >
                    <template #edit="{ row }" v-if="item.editAuth">
                        <vxe-input v-model="row[columns.field]" type="text" v-if="columns.type === 'STRING' ||
                            columns.type === 'TEXT'"></vxe-input>
                        <vxe-input v-model="row[columns.field]" type="number" v-if="columns.type === 'NUMBER'"></vxe-input>
                        <vxe-input v-model="row[columns.field]" type="date" v-if="columns.type === 'DATE'"></vxe-input>
                        <vxe-input v-model="row[columns.field]" type="datetime"
                            v-if="columns.type === 'DATE_TIME'"></vxe-input>
                    </template>
                </vxe-column>
            </vxe-table>
        </div><vxe-toolbar ref="xToolbar" size="small" class-name="execute-result-table-toolbar">
            <template #buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <div>{{ item.sql }}</div>
                    </el-col>
                    <el-col :span="1.5">
                        <div>执行时长：{{ item.time / 1000 }}秒</div>
                    </el-col>
                    <el-col :span="1.5">
                        <div>总条数：{{ item.total }}</div>
                    </el-col>
                    <el-col :span="1.5">
                        <div>{{ item.editAuth ? '' : '只读模式' }}</div>
                    </el-col>
                </el-row>


            </template>
            <template #tools>
                <el-pagination v-model:current-page="item.pageIndex" v-model:page-size="item.pageSize" :total="item.total"
                    :small="true" :page-sizes="[10, 50, 100, 500]" v-if="!item.noPage" layout="sizes, prev,  next, jumper"
                    @size-change="executeResultPageHandle(item, index)"
                    @current-change="executeResultPageHandle(item, index)" />
            </template>
        </vxe-toolbar>
    </div>
</template>
<script setup>
import { ref, defineProps, inject, h, computed, reactive, toRefs, watch, defineExpose,nextTick } from 'vue'
import { SqlBuilder } from '@/plugins/sql/SqlBuilder'
import _ from "lodash"
import key from 'keymaster'
//接收数据
const props = defineProps({
    item: {
        type: Object,
        default: {

        }
    },
    catalog: {
        type: String,
        default: undefined
    },
    connId: {
        type: String,
        default: undefined
    },
    pluginId: {
        type: String,
        default: undefined
    },
    executeResultResizerValue: {
        type: [Number, String],
        default: 315
    }
});
//参数
const $bus = inject('$bus')
const $config = inject('$config')
const $api = inject('$api');
const $message = inject('$message');
const $messageBox = inject('$messageBox');
const $cacheStore = inject("$cacheStore");
const $pluginService = inject("$pluginService")
console.log($cacheStore)
const sqlHandle = new SqlBuilder();
const item = ref(props.item);
const catalog = ref(props.catalog)
const connId = ref(props.connId)
const pluginId = ref(props.pluginId)
const executeResultResizerValue = ref(props.executeResultResizerValue)
const oldItem = _.cloneDeep(item.value)
const deleteCheckboxState = ref(false);
const dataEditState = ref(false);
const copyCacheRow = ref("");
const tableLoading  = ref(false)

//表和工具栏的ref
const xTable = ref(null);
const xToolbar = ref(null);

//函数
const executeResultResizerValue1 = computed(() => {
    const height = isNaN(Number(executeResultResizerValue.value, 10)) ? executeResultResizerValue.value : `${executeResultResizerValue.value}px`
    return height;
});

const insertHandle = (item) => {
    const row = -1;
    debugger
    const record = item;
    xTable.value.insertAt(record, row).then(({ row }) => {
        xTable.value.setEditRow(row);
        xTable.value.setCurrentRow(row)
    })
}
//删除记录
const deleteHandle = () => {
    let rows = xTable.value.getCheckboxRecords(false)
    if (rows.length == 0) {
        return
    }
    $messageBox.confirm(
        `确定要删除${rows.length}条记录?`,
        '消息',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let sqls = sqlHandle.deleteRowCovert(item.value.tableName, item.value.columns, rows);
            executeSqlScript(sqls.join(""))
                .then((res => {
                    if (res.data[0].success) {

                        xTable.value.removeCheckboxRow();
                        xTable.value.clearCheckboxRow();
                        $message.success('删除成功');
                    } else {
                        $message.error(res.data[0].message);
                    }

                }))

        })
        .catch((e) => {
            console.error(e)
        })

}

//提交编辑
const submitEditHandle = () => {
    const insertRows = xTable.value.getInsertRecords()
    // const deleteRows = item.ref.getRemoveRecords()
    const updatetRows = xTable.value.getUpdateRecords()
    if (insertRows.length == 0 && updatetRows.length == 0) {
        return;
    }
    if (!connId) {
        item.ref.loadData(oldItem.rows);
        return;
    }
    const pluginJs =$pluginService.getPlugin(props.pluginId)
    let sqlHandler = sqlHandle;
    if (pluginJs && pluginJs.sqlBuilder) {
        sqlHandler = pluginJs.sqlBuilder;
    }
    let arr = [];
    if (insertRows.length > 0) {
        arr.push(sqlHandler.insertRowCovert(item.value.tableName, item.value.columns, insertRows))
    }
    // if (deleteRows.length > 0) {
    //     arr.push(...sqlHandler.deleteRowCovert(item.tableName, item.columns, deleteRows))
    // }
    if (updatetRows.length > 0) {
        arr.push(...sqlHandler.updateRowCovert(item.value.tableName, item.value.columns, updatetRows))
    }
    executeSqlScript(arr.join(""))
        .then((res => {
            if (res.data[0].success) {
                $message.success('修改成功');

            } else {
                $message.error(res.data[0].message);
            }
        }))
        .finally(() => {
            xTable.value.clearAll();
            executeResultPageHandle();
            dataEditState.value = false;
            deleteCheckboxState.value = false;
        })

}

const cancelEditHandle = () => {
    $messageBox.confirm(
        `确定要放弃修改?`,
        '消息',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            xTable.value.loadData(oldItem.rows);
            dataEditState.value = false;
        })
        .catch(() => {
        })
}
const refreshDataHandle = () => {
    executeResultPageHandle().then((res) => {
        $message.success('刷新成功');
    })
}

const executeResultCellHandle = ({ row, column }) => {
    //  if (column.cellType === 'TEXT') {
    $bus.$emit($config.TEXT_VALUE_VIESER, { data: { value: row[column.field] }, type: 'dataViewer' })
    //  }

}
const checkboxChangeHandle = (r) => {
    let rows = xTable.value.getCheckboxRecords(false)
    if (rows.length > 0) {
        deleteCheckboxState.value = true;
        return;
    }
    deleteCheckboxState.value = false;
}

const dataEditStateHandle = (r) => {
    const insertRows = xTable.value.getInsertRecords()
    // const deleteRows = item.ref.getRemoveRecords()
    const updatetRows = xTable.value.getUpdateRecords()
    if (insertRows.length > 0 || updatetRows.length > 0) {
        dataEditState.value = true;
    } else {
        dataEditState.value = false;
    }

}

const executeResultPageHandle = () => {
    return new Promise((resolve, reject) => {
        tableLoading.value = true;
        const executeParams = { script: item.value.sql, pageIndex: item.value.pageIndex, pageSize: item.value.pageSize, noPage: item.value.noPage };
        const params = { connId: connId.value, catalog: catalog.value, executeParams: executeParams };
        //请求后台获取子节点数据
        $api.sqlDatabase
            .executeSqlScript(params)
            .then((res) => {

                item.value = _.cloneDeep(res.data[0])
                item.value.rows = res.data[0].rows
                item.value.columns = res.data[0].columns
                return resolve(res);
            })
            .catch(e => {
                reject(e)
            })
            .finally(()=>tableLoading.value=false)

    });
}

const executeSqlScript = (sql) => {
    return new Promise((resolve, reject) => {
        const executeParams = { script: sql, noPage: true };
        const params = { connId: connId.value, catalog: catalog.value, executeParams: executeParams };
        //请求后台获取子节点数据
        $api.sqlDatabase
            .executeSqlScript(params)
            .then((res) => {
                return resolve(res);
            })
            .catch(e => {
                reject(e)
            })

    });

}

const copyEventHandle = ()=>{
    console.log("askldjflaksjd")
}

const init = () => {
    nextTick(()=>{
        key('ctrl+c', () => {
            const row = xTable.value.getCurrentRecord();
            if (!row) {
                $message.warning("请选择一行数据");
                return
            }
            copyCacheRow.value = row;
           // xTableValue.clearCurrentRow();
            return true
        });
        key('ctrl+v', () => {
            if (copyCacheRow.value) {
                const row = xTable.value.getCurrentRecord();
                if (row == null || !xTable.value.isEditByRow(row)) {
                    insertHandle(copyCacheRow.value);
                } else {
                     Object.assign(row, copyCacheRow.value)
                     xTable.value.setCurrentRow(row)
                }

            }
            return true
        });
    })

}
init();
//重新刷新组件
const reload = () => {
    refreshDataHandle();
}
//设置可访问参数和方法
defineExpose({ reload })
</script>

<style lang="scss" scoped>
.execute-result-box {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
}

.execute-result-table-toolbar {
    padding: 0px 5px 5px 5px;
}

/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
    width: 12px;
    height: 12px;
}

/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
    background-color: #FFFFFF;
}

/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
    background-color: #bfbfbf;
    border-radius: 5px;
    border: 1px solid #F1F1F1;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
    background-color: #A8A8A8;
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
    background-color: #787878;
}

/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
    background-color: #FFFFFF;
}
</style>